package semaphore;

import java.util.concurrent.Semaphore;

public class ThreadSemaphore {
	public static void main(String[] args) {
		  Semaphore full=new Semaphore(0,true);
		  Semaphore empty=new Semaphore(5,true);
		  Semaphore mutex=new Semaphore(1,true);
		  int[] in_out=new int[2];
		  Producer p=new Producer(full,empty,mutex,in_out);
		  Consumer c=new Consumer(full,empty,mutex,in_out);
		  p.start();
		  c.start();
	}

}
class Consumer extends Thread{
	Semaphore full;
	Semaphore empty;
	Semaphore mutex;
	int[] in_out;
    public Consumer(Semaphore full,Semaphore empty,Semaphore mutex,int[] in_out)
    {
    	this.full=full;
    	this.empty=empty;
    	this.mutex=mutex;
    	this.in_out=in_out;
    }
	public void run()
	{
	  
	  try {
	    while(true)
	    {	 
	    	full.acquire();
	    	mutex.acquire();
	    	this.in_out[1]++;
			System.out.println(in_out[0]-in_out[1]);
			mutex.release();
			empty.release();
		   Thread.sleep(250);
	    }
	  } catch (Exception e) {
			e.printStackTrace();
		}
	}
}
class Producer extends Thread{

	Semaphore full;
	Semaphore empty;
	Semaphore mutex;
	int[] in_out;
    public Producer(Semaphore full,Semaphore empty,Semaphore mutex,int[] in_out)
    {
    	this.full=full;
    	this.empty=empty;
    	this.mutex=mutex;
    	this.in_out=in_out;
    }
	public void run()
	{
  
	  try {
	    while(true)
	    {
	       empty.acquire();
	       mutex.acquire();
		   this.in_out[0]++;
		    System.out.println(in_out[0]-in_out[1]);
		   mutex.release();
		   full.release();
		   Thread.sleep(200);
	    }
	  } catch (Exception e) {
			e.printStackTrace();
		}
	}
}
